package com.javacv.plus.examples;

import com.javacv.plus.extensions.image.ImageProcessor;
import com.javacv.plus.extensions.batch.BatchProcessor;
import com.javacv.plus.platform.PlatformDetector;
import com.javacv.plus.platform.SystemInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 性能测试程序
 * 测试JavaCV Plus的性能表现
 */
@Slf4j
public class PerformanceTest {

    public static void main(String[] args) {
        log.info("=== JavaCV Plus 性能测试 ===");
        
        try {
            // 显示系统信息
            showSystemInfo();
            
            // 1. 测试API调用性能
            testApiPerformance();
            
            // 2. 测试内存使用
            testMemoryUsage();
            
            // 3. 测试并发性能
            testConcurrentPerformance();
            
            log.info("\n🎉 性能测试完成！");
            
        } catch (Exception e) {
            log.error("性能测试过程中发生错误", e);
        }
    }

    /**
     * 显示系统信息
     */
    private static void showSystemInfo() {
        log.info("\n💻 系统信息");
        log.info("========================");
        
        SystemInfo systemInfo = PlatformDetector.getSystemInfo();
        log.info("操作系统: {} {}", systemInfo.getOsName(), systemInfo.getOsVersion());
        log.info("系统架构: {}", systemInfo.getOsArch());
        log.info("CPU核心数: {}", systemInfo.getAvailableProcessors());
        log.info("最大内存: {} MB", systemInfo.getMaxMemory() / 1024 / 1024);
        log.info("可用内存: {} MB", systemInfo.getFreeMemory() / 1024 / 1024);
    }

    /**
     * 测试API调用性能
     */
    private static void testApiPerformance() {
        log.info("\n⚡ API调用性能测试");
        log.info("========================");
        
        int iterations = 1000;
        long startTime = System.nanoTime();
        
        // 测试处理器创建性能
        for (int i = 0; i < iterations; i++) {
            try {
                ImageProcessor processor = ImageProcessor.of("test" + i + ".jpg")
                    .resize(800, 600)
                    .blur(5)
                    .brightness(1.1);
                // 不实际执行，只测试API调用
            } catch (Exception e) {
                // 忽略文件不存在的错误
            }
        }
        
        long endTime = System.nanoTime();
        long duration = endTime - startTime;
        double avgTime = duration / (double) iterations / 1_000_000; // 转换为毫秒
        
        log.info("✅ API调用性能测试完成");
        log.info("   - 迭代次数: {}", iterations);
        log.info("   - 总耗时: {:.2f} ms", duration / 1_000_000.0);
        log.info("   - 平均耗时: {:.3f} ms/次", avgTime);
        log.info("   - QPS: {:.0f} 次/秒", 1000.0 / avgTime);
    }

    /**
     * 测试内存使用
     */
    private static void testMemoryUsage() {
        log.info("\n🧠 内存使用测试");
        log.info("========================");
        
        Runtime runtime = Runtime.getRuntime();
        
        // 测试前的内存状态
        runtime.gc(); // 强制垃圾回收
        long memoryBefore = runtime.totalMemory() - runtime.freeMemory();
        
        log.info("测试前内存使用: {} MB", memoryBefore / 1024 / 1024);
        
        // 创建多个处理器实例
        List<ImageProcessor> processors = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            try {
                ImageProcessor processor = ImageProcessor.of("test" + i + ".jpg")
                    .resize(1920, 1080)
                    .gaussianBlur(3.0)
                    .brightness(1.1)
                    .contrast(1.2);
                processors.add(processor);
            } catch (Exception e) {
                // 忽略错误
            }
        }
        
        // 测试后的内存状态
        long memoryAfter = runtime.totalMemory() - runtime.freeMemory();
        long memoryUsed = memoryAfter - memoryBefore;
        
        log.info("✅ 内存使用测试完成");
        log.info("   - 创建处理器数量: {}", processors.size());
        log.info("   - 测试后内存使用: {} MB", memoryAfter / 1024 / 1024);
        log.info("   - 内存增长: {} MB", memoryUsed / 1024 / 1024);
        log.info("   - 平均每个处理器: {} KB", memoryUsed / processors.size() / 1024);
        
        // 清理资源
        processors.clear();
        runtime.gc();
    }

    /**
     * 测试并发性能
     */
    private static void testConcurrentPerformance() {
        log.info("\n🔄 并发性能测试");
        log.info("========================");
        
        int[] threadCounts = {1, 2, 4, 8};
        
        for (int threadCount : threadCounts) {
            testBatchProcessorPerformance(threadCount);
        }
        
        log.info("✅ 并发性能测试完成");
        log.info("   建议: 根据CPU核心数选择合适的并发数");
    }

    /**
     * 测试批量处理器性能
     */
    private static void testBatchProcessorPerformance(int threadCount) {
        try {
            BatchProcessor batchProcessor = new BatchProcessor(threadCount);
            
            long startTime = System.currentTimeMillis();
            
            // 模拟处理任务
            List<Runnable> tasks = new ArrayList<>();
            for (int i = 0; i < 50; i++) {
                final int taskId = i;
                tasks.add(() -> {
                    try {
                        // 模拟处理时间
                        Thread.sleep(10);
                        ImageProcessor.of("task" + taskId + ".jpg")
                            .resize(800, 600)
                            .blur(3);
                    } catch (Exception e) {
                        // 忽略错误
                    }
                });
            }
            
            // 等待任务完成（简化版本）
            Thread.sleep(100);
            
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            
            log.info("   线程数: {} - 耗时: {} ms", threadCount, duration);
            
            batchProcessor.shutdown();
            
        } catch (Exception e) {
            log.warn("并发测试线程数 {} 时发生错误: {}", threadCount, e.getMessage());
        }
    }
} 